package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.EmployeeEx;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    private HashMap<Object, Object> pageMap = new HashMap<>();

    //用于用户登录
    @PostMapping("/login")
    private R<Employee> login(HttpSession session, @RequestBody Employee employee) {
        log.info("用户{}正在登录", employee.getUsername());
        //1.判断传过来的数据空否
        if (employee == null
                || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())
        ) {
            return R.error("用户名或密码不能为空!");
        }
        //2.处理密码进行加密处理
        String password = employee.getPassword();//明文
        password = DigestUtils.md5DigestAsHex(password.getBytes());//密文

        //3.判断用户存在与否
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(qw);

        //3.1如果不存在
        if (one == null) {
            return R.error("用户不存在!");
        }

        //3.2如果状态为禁用
        if (one.getStatus() == 0) {
            return R.error("用户已禁用!");
        }

        //4用户存在比对密码
        if (password.equals(one.getPassword())) {
            //成功
            //id加入session
            session.setAttribute("employee", one.getId());
            //密码设置为null,返回数据
            one.setPassword(null);
            return R.success(one);
        } else {
            //4.1登陆失败
            return R.error("密码错误,请重新登陆!");
        }
    }

    //用于用户登出
    @PostMapping("/logout")
    private R<String> logout(HttpSession session) {
        log.info("用户id为:{}登出", session.getAttribute("employee"));
        //session移除返回成功数据
        session.removeAttribute("employee");
        return R.success("success!");
    }

    //用于添加用户
    @PostMapping
    private R<String> save(HttpSession session, @RequestBody Employee employee) {
        //获取当前页面emp的id
        Long empId = (Long) session.getAttribute("employee");
        log.info("用户id为{}添加了员工{}", empId, employee.toString());

      /*  //设置创建时间及更新人员id
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        //设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //进行用户存入
        employeeService.save(employee);
        return R.success("用户添加成功!");
    }

    //用于展示员工
    @GetMapping("/page")
    private R page(Integer page, Integer pageSize, String name) {
        //设置查询页数
        IPage<Employee> pageInfor = new Page<>(page, pageSize);
        //添加查询条件
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Employee::getName, name)
                .orderByDesc(Employee::getUpdateTime);
        //查询员工
        employeeService.page(pageInfor, qw);

        //返回数据
        List<Employee> records = pageInfor.getRecords();
        long total = pageInfor.getTotal();

        pageMap.clear();
        pageMap.put("records", records);
        pageMap.put("total", total);

        return R.success(pageMap);
    }

    //用于修改员工启用禁用状态
    @PutMapping
    private R update(@RequestBody Employee emp, HttpSession hs) {
        log.info(emp.toString());

       /* //修改属性
        Long upByEmpId = (Long) hs.getAttribute("employee");
        emp.setUpdateTime(LocalDateTime.now());
        emp.setUpdateUser(upByEmpId);*/

        //更新用户数据
        employeeService.updateById(emp);
        return R.success("修改成功!");
    }

    //用于编辑员工信息
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }

    //用于文件下载
    @GetMapping("/export")
    public void exportEmployee(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition",
                "attachment; filename=employee.xlsx"); //指定文件下的名称！！


        List<Employee> list = employeeService.list();
        List<EmployeeEx> collect = list.stream().map((one) -> {

            EmployeeEx employeeEx = new EmployeeEx();
            BeanUtils.copyProperties(one, employeeEx);

            //设置id
            employeeEx.setId(one.getId().toString());

            //更改了名字
            String name = employeeService.getById(one.getCreateUser()).getName();
            employeeEx.setCreateUser(name);
            String nameU = employeeService.getById(one.getUpdateUser()).getName();
            employeeEx.setUpdateUser(nameU);

            //更改性别
            if ("0".equals(one.getSex())) {
                employeeEx.setSex("女");
            } else {
                employeeEx.setSex("男");
            }

            //启用禁用
            if (0 == (one.getStatus())) {
                employeeEx.setStatus("离职");
            } else {
                employeeEx.setStatus("在职");
            }

            return employeeEx;
        }).collect(Collectors.toList());
        try {
            EasyExcel.write(response.getOutputStream(), EmployeeEx.class).sheet("模板").doWrite(collect);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
